package cn.yunhe.action;

import cn.yunhe.entity.User;
import cn.yunhe.service.UserService;
import com.opensymphony.xwork2.ModelDriven;

import java.util.Set;

public class UserAction extends  BaseAction implements ModelDriven<User> {

    private  User user;
    private UserService userService = new UserService();
    private  static int loginTimes =1;

    public String login(){

        User u = userService.login(user);

        if (u==null){
            getSession().setAttribute("msg","用户名或密码错误");
            getSession().setAttribute("loginTimes",loginTimes++);
            return ERROR;
        }

            Set<User> onlineUsers = (Set<User>) getApplication().getAttribute("onlineUsers");

            for (User userList : onlineUsers) {
                if (u.getName().equals(userList.getName())) {
                    //该用户正在被使用
                    getSession().setAttribute("loginTimes",loginTimes++);
                    getSession().setAttribute("msg", "该用户已登录,如不是本人操作,请尽快修改密码");
                    return ERROR;
                }
        }

        if (u!=null){//登陆成功
            getSession().setAttribute("Curr_User",u);//将用户存至session
            return SUCCESS;
        }else {
            return ERROR;
        }
    }

   public String reg(){
       user.setMargin(1);
       boolean flag =  userService.reg(user);
       if (flag){
           return SUCCESS;
       }else {
           return ERROR;
       }
   }


    @Override
    public User getModel() {
        if (user == null ){
           user = new User();
        }
        return user;
    }
}
